package com.demo.config.shiro.realm;

import cn.hutool.core.util.ObjectUtil;
import com.demo.modules.sys.entity.SysUserEntity;
import com.demo.modules.sys.service.ShiroService;
import com.demo.modules.sys.service.SysUserService;
import com.demo.modules.sys.service.SysUserTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 登录认证
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private ShiroService shiroService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
        Long userId = user.getId();

        //用户权限列表
        Set<String> permsSet = shiroService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken paramAuthenticationToken) throws AuthenticationException {
        // 获取认证token对象
        UsernamePasswordToken token = (UsernamePasswordToken) paramAuthenticationToken;

        // 获取用户对象
        SysUserEntity user = sysUserService.queryByUserName(token.getUsername());

        // 用户不存在
        if (ObjectUtil.isEmpty(user)) {
            throw new UnknownAccountException();
        }

        // 账号锁定
        if (user.getStatus() == 0) {
            throw new LockedAccountException();
        }

        // 密码加密
        token.setPassword(new Sha256Hash(token.getPassword(), user.getSalt()).toHex().toCharArray());

        // 认证
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

}
